import 'package:inmotion_pro/config/r.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/routes/app_routes.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:ble_helper_plugin/library.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import '../others/common_enum/vehicle_function_button_type.dart';
import '../mixin/vehicle_type_mixin.dart';
import 'controller.dart';
import 'widgets/cycling_record_cover.dart';
import 'widgets/vehicle_top_info_view.dart';
import 'widgets/vehicle_fuction_buttons_view.dart';

// 车辆页面
class VehicleView extends BaseGetView<VehicleController> with VehicleTypeMixin {
  VehicleView({super.key});

  @override
  VehicleController get controller => Get.find(tag: AppRoutes.VEHICLE);

  // 检查当前页面是否处于活动状态
  bool isCurrentPageActive(BuildContext context) {
    return ModalRoute.of(context)?.isCurrent ?? false;
  }

  @override
  Widget build(BuildContext context) {
    final double navHeight = 80.w;
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          WaterMarkView(
            // 水印
            text: context.s.tourist_mode,
            opacity: GlobalService.to.isLoggedIn ? 0 : 0.1,
            color: Colors.white,
            lxFontWeight: LxFontWeightEnum.headlineSmall,
            spacing: 2 * screenWidth / 3,
            child: Container(
              color: Colors.black,
              child: _buildBody(context, navHeight),
            ),
          ),
          // 自定义渐变导航栏
          Obx(() {
            return Visibility(
              visible: GlobalService.to.cacheVehicleList.isNotEmpty,
              child: Container(
                color: Colors.black.withOpacity(
                    (controller.state.currentScrollOffset.value / 50)
                        .clamp(0, 1)),
                height: navHeight,
                child: Column(
                  children: [
                    SizedBox(height: statusBarHeight),
                    Expanded(
                      child: Center(
                        child: _buildBleName(), // 蓝牙名称
                      ),
                    )
                  ],
                ),
              ),
            );
          }),
          // 可拖动的悬浮按钮
          _buildDraggableFloatingButton(),
        ],
      ),
    );
  }

  // 构建主页面
  _buildBody(BuildContext context, double navHeight) {
    return Obx(
      () {
        // 当前车辆类型
        final vehicleType = vehicleTypeMixinGetVehicleType(
            bleName: GlobalService.to.currentVehicleModel.value.bleName);
        // 非游客模式下人机版状态
        bool isHmicStatus = !GlobalService.to.isGuest &&
            GlobalService.to.currentVehicleModel.value.hmicStatus;
        return Visibility(
          visible: GlobalService.to.cacheVehicleList.isNotEmpty,
          // 无缓存车辆，显示搜索车辆按钮
          replacement: Container(
            color: Colors.black,
            height: screenHeight - statusBarHeight - navigationBarHeight,
            child: _buildSearchVehicleView(context),
          ),
          child: Stack(
            children: [
              Visibility(
                visible: GlobalService
                    .to.currentVehicleModel.value.bleName.isNotEmpty,
                child: NotificationListener<ScrollNotification>(
                  onNotification: (scrollNotification) {
                    if (scrollNotification is ScrollUpdateNotification) {
                      // 实时获取滚动位置
                      controller.state.currentScrollOffset.value =
                          scrollNotification.metrics.pixels;
                    }
                    return false; // 返回 false 允许通知继续传递
                  },
                  child: SingleChildScrollView(
                    physics: const BouncingScrollPhysics(),
                    child: Column(
                      children: [
                        SizedBox(height: navHeight),
                        // 顶部信息
                        VehicleTopInfoView(
                          vehiclePath: controller
                                          .state.bluetoothConnectState.value ==
                                      CustomBluetoothConnectState.connected ||
                                  isHmicStatus
                              ? vehicleType.assetPath
                              : vehicleType.greyAssetPath,
                          batteryLevel:
                              controller.state.currentBatteryLevel.value,
                          remainingMileage:
                              controller.state.currentRemainingMileage.value,
                          warningMsgList: controller.state.warningMsgList,
                          bluetoothConnectState:
                              controller.state.bluetoothConnectState.value,
                          tboxSignalLevel:
                              controller.state.tboxSignalLevel.value,
                          isOwner: GlobalService
                              .to.currentVehicleModel.value.isOwner.value,
                          tboxStatusType: GlobalService
                              .to.currentVehicleModel.value.tboxStatus.value,
                          bluetoothOnTap: controller.bluetoothConnectOnTap,
                          wifiOnTap: controller.lockVehicleOnTap,
                          warningOnTap: controller.warningOnTap,
                        ),

                        SizedBox(height: CONTENT_MARGIN),

                        // 功能区
                        Padding(
                          padding: EdgeInsets.only(
                            left: CONTENT_MARGIN,
                            right: CONTENT_MARGIN,
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(CONTENT_MARGIN),
                            child: VehicleFunctionButtonsView(
                              totalMileage: controller.state.totalMileage.value,
                              isLocked: controller.state.isLocked.value,
                              onTap: (p0) {
                                switch (p0) {
                                  case VehicleFunctionButtonType.lock:
                                    controller.lockVehicleOnTap();
                                    break;
                                  case VehicleFunctionButtonType.horn:
                                    controller.hornOnTap();
                                    break;
                                  case VehicleFunctionButtonType.light:
                                    controller.lightOnTap();
                                    break;
                                  case VehicleFunctionButtonType.settings:
                                    controller.vehicleSettingOnTap();
                                    break;
                                  case VehicleFunctionButtonType.realtimeDetail:
                                    controller.realtimeDetailOnTap();
                                    break;
                                }
                              },
                              buttonTypes:
                                  controller.state.getVehicleFunctionButtons,
                            ),
                          ),
                        ),

                        SizedBox(height: CONTENT_MARGIN),

                        // 骑行记录/车辆定位
                        Padding(
                          padding: EdgeInsets.only(
                            left: CONTENT_MARGIN,
                            right: CONTENT_MARGIN,
                          ),
                          child: _cyclingRecordCover(),
                        ),

                        SizedBox(height: CONTENT_MARGIN),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 蓝牙名称
  _buildBleName() {
    double imgWidth = 20.w;
    double navigationButtonWidth = 44.w;
    final vehicleModel = GlobalService.to.currentVehicleModel.value;
    return SizedBox(
      height: navigationButtonWidth,
      child: Stack(
        children: [
          // 返回按钮
          Visibility(
            visible: !GlobalService.to.isLoggedIn,
            child: LxButton(
              customIcons: [Image.asset(R.navPopArrowIcon)],
              height: navigationButtonWidth,
              buttonTypeCustomColor: ButtonTypeColor()
                ..borderColor = Colors.transparent
                ..backgroundColor = Colors.transparent
                ..textColor = LxCol.theme,
              onTap: () => Get.back(),
            ),
          ),

          // 更多按钮
          Positioned(
            right: 0,
            child: LxButton(
              height: navigationButtonWidth,
              customIcons: [Image.asset(R.moreIcon)],
              buttonTypeCustomColor: ButtonTypeColor()
                ..borderColor = Colors.transparent
                ..backgroundColor = Colors.transparent
                ..textColor = Colors.white,
              onTap: () {
                controller.moreFunctionOnTap();
              },
            ),
          ),

          Container(
            width: double.infinity,
            constraints: BoxConstraints(minHeight: navigationBarHeight),
            child: GestureDetector(
              onTap: controller.switchVehicleOnTap,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                mainAxisSize: MainAxisSize.min,
                children: [
                  // 蓝牙名称
                  Center(
                    child: Container(
                      constraints: BoxConstraints(
                        maxWidth: screenWidth -
                            2 * navigationButtonWidth -
                            imgWidth -
                            2 * CONTENT_MARGIN,
                      ),
                      child: Obx(
                        () => LxText(
                          vehicleModel.nickname.value.isNotEmpty
                              ? vehicleModel.nickname.value
                              : vehicleModel.bleName,
                          color: Colors.white,
                          fontWeightEnum: LxFontWeightEnum.titleExtraLarge,
                          maxLines: 1,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(width: 4.w),
                  // 切换车辆按钮
                  Image.asset(
                    R.switchVehicleIcon,
                    width: imgWidth,
                    height: imgWidth,
                    fit: BoxFit.fitWidth,
                  ).colorFiltered(color: Colors.white),
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建搜索车辆按钮
  Widget _buildSearchVehicleView(BuildContext context) {
    return Center(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          LxText(
            context.s.prompt_welcome_to_inmotion,
            color: Colors.white.withOpacity(0.8),
            fontWeightEnum: LxFontWeightEnum.headlineMedium,
            lineHeight: 1.35,
          ),
          SizedBox(height: CONTENT_MARGIN * 4),
          // 车辆图片
          Image.asset(
            R.v12s,
            width: double.infinity,
            height: 245.w,
            fit: BoxFit.fitHeight,
          ),
          SizedBox(
            width: screenWidth - 180.w,
            child: Padding(
              padding: EdgeInsets.only(top: 20.w),
              child: LxButton(
                height: 40.w,
                title: context.s.search_for_vehicles,
                borderRadius: BorderRadius.circular(20.w),
                buttonSizeEnum: ButtonSizeEnum.medium,
                onTap: () {
                  controller.searchVehicleOnTap();
                },
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 骑行记录封面
  Widget _cyclingRecordCover() {
    final model = controller.state.flashLatestCyclingRecord.value;
    return ClipRRect(
      borderRadius: BorderRadius.circular(CONTENT_MARGIN),
      child: Material(
        color: Colors.transparent, // 使用Material包裹，保证水波纹效果
        child: Visibility(
          visible: model != null,
          replacement: const CyclingRecordCover(),
          child: CyclingRecordCover(
            hasRecord: true,
            rideDate: model?.date,
            rideDuration: model?.ridingDuration,
            rideDistance: (model?.mileage ?? 0) / 100,
            onMorePressed: () {
              controller.cyclingRecordOnTap();
            },
          ),
        ),
      ),
    );
  }

  // 可拖动的悬浮按钮
  _buildDraggableFloatingButton() {
    return Obx(() {
      final vehicleModel = GlobalService.to.currentVehicleModel.value;
      return Visibility(
        visible: vehicleModel.bleName.isNotEmpty &&
            GlobalService.to.isLoggedIn &&
            vehicleModel.isOwner.value != null && // 因为默认null，此时也不可以显示悬浮按钮
            vehicleModel.isOwner.value == false,
        child: DraggableFloatingButton(
          initialOffset: Offset(0, appBarHeight + 80.w),
          preferredEdge: PreferredEdge.right,
          margin: EdgeInsets.only(
            top: appBarHeight + 20.w,
            bottom: tabBarSpace + 120.w,
          ),
          enableHapticFeedback: true,
          enableEdgeElasticity: true,
          savePosition: true,
          animationDuration: const Duration(milliseconds: 500),
          animationCurve: Curves.elasticOut,
          onPressed: () {
            // 点击悬浮按钮，认证车辆
            controller.goAuthOwnerOnTap();
          },
          child: Container(
            padding: EdgeInsets.symmetric(
              horizontal: 10.w,
              vertical: 6.w,
            ),
            // 设置左边上下圆角为100
            decoration: BoxDecoration(
              color: GrayColor.gray2,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(100.w),
                bottomLeft: Radius.circular(100.w),
              ),
            ),
            child: IntrinsicWidth(
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Image.asset(
                    R.authOwnerIcon,
                    width: 30.w,
                    fit: BoxFit.fill,
                  ),
                  SizedBox(width: 4.w),
                  LxText(
                    local.go_auth_owner,
                    color: Colors.white,
                    fontWeightEnum: LxFontWeightEnum.titleSmall,
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    });
  }
}
